package com.hjx.windowtool.video;

import java.awt.EventQueue;
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDropEvent;

import javax.swing.JFrame;
import javax.swing.JSplitPane;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;

import org.joda.time.DateTime;

import com.hjx.windowtool.util.MyAppender;

import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JFileChooser;

import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.awt.event.ActionEvent;

public class SubTitleChangeApp {

	private JFrame frame;
	private JTextField txt_old;
	private JTextField txt_new;
	private JTextField txt_oldStart;
	private JTextField txt_endStart;
	private JTextArea txt_msg;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					SubTitleChangeApp window = new SubTitleChangeApp();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public SubTitleChangeApp() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 643, 384);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JSplitPane splitPane = new JSplitPane();
		splitPane.setResizeWeight(0.5);
		splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
		frame.getContentPane().add(splitPane, BorderLayout.CENTER);
		
		JPanel panel = new JPanel();
		splitPane.setLeftComponent(panel);
		panel.setLayout(null);
		
		JLabel label = new JLabel("旧");
		label.setBounds(36, 20, 21, 15);
		panel.add(label);
		
		JLabel label_1 = new JLabel("新");
		label_1.setBounds(36, 57, 21, 15);
		panel.add(label_1);
		
		txt_old = new JTextField();
		txt_old.setBounds(67, 17, 402, 21);
		panel.add(txt_old);
		txt_old.setColumns(10);
		txt_old.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount()>2) {
					JFileChooser f = new JFileChooser();
					f.setFileSelectionMode(JFileChooser.FILES_ONLY);
					int showOpenDialog = f.showOpenDialog(frame);
					if (showOpenDialog==0) {
						File selectedFile = f.getSelectedFile();
						txt_old.setText(selectedFile.getAbsolutePath());
					}
				}
			}
		});
		
		addFileDropTarget(txt_old,false);
		
		txt_new = new JTextField();
		txt_new.setBounds(67, 54, 402, 21);
		panel.add(txt_new);
		txt_new.setColumns(10);
		
		addFileDropTarget(txt_new,false);
		
		txt_oldStart = new JTextField();
		txt_oldStart.setText("UTF-8");
		txt_oldStart.setBounds(487, 17, 73, 21);
		panel.add(txt_oldStart);
		txt_oldStart.setColumns(10);
		
		txt_endStart = new JTextField();
		txt_endStart.setText("UTF-16");
		txt_endStart.setBounds(487, 54, 73, 21);
		panel.add(txt_endStart);
		txt_endStart.setColumns(10);
		
		JButton button = new JButton("替换");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					List<String> listOld = Files.readAllLines(Paths.get(txt_old.getText()), Charset.forName(txt_oldStart.getText()));
					int index=0;
					for (int i = 0; i < listOld.size(); i++) {
						String string = listOld.get(i);
						System.out.println(string);
						if (string.startsWith("Dialogue")) {
							index=i;
							break;
						}
					}
					List<String> list = listOld.stream().filter(s->s.startsWith("Dialogue")).collect(Collectors.toList());
					String oldTime = list.get(0).split(",")[1];
					System.out.println(oldTime);
//					for (int i = 0; i < list.size(); i++) {
//						String string = list.get(i);
//						System.out.println(string);
//						int showIndex = getShowIndex(string, ",", 9);
////						System.out.println(i+"=="+string.substring(showIndex));
//					}
					List<String> listNew = Files.readAllLines(Paths.get(txt_new.getText()), Charset.forName(txt_endStart.getText()));
					System.out.println(listNew);
					List<String> collect = listNew.stream().filter(s->s.startsWith("Dialogue")).collect(Collectors.toList());
					System.out.println(collect.get(0));
					String newTime = collect.get(0).split(",")[1];
					SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss.SSS");
					long sub=sdf.parse(oldTime).getTime()-sdf.parse(newTime).getTime();
					System.out.println(sub);
					System.out.println(newTime);
					List<String> listnn=new ArrayList<>();
					for (int i = 0; i < listNew.size(); i++) {
						String string = listNew.get(i);
						if (!string.startsWith("Dialogue")) {
							listnn.add(string);
							continue;
						}
						System.out.println(string);
						String[] ss = string.split(",");
						ss[1]=sdf.format(new Date(sdf.parse(ss[1]).getTime()+sub));
						ss[2]=sdf.format(new Date(sdf.parse(ss[2]).getTime()+sub));
						String join = String.join(",", ss);
						System.out.println(join);
						listnn.add(join);
					}
					Files.write(Paths.get(txt_new.getText()+"_new.ass"), listnn,Charset.forName(txt_endStart.getText()));
					
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		});
		button.setBounds(67, 85, 93, 23);
		panel.add(button);
		
		txt_msg = new JTextArea();
		txt_msg.setWrapStyleWord(true);
		splitPane.setRightComponent(txt_msg);
		init();
	}
	
	public int getShowIndex(String s, String show, int size) {
		Pattern pattern = Pattern.compile(show);
		Matcher findMatcher = pattern.matcher(s);
		int number = 0;
		while (findMatcher.find()) {
			number++;
			if (number == size) {// 当“A”第二次出现时停止
				break;
			}
		}
		int i = findMatcher.start();// “A”第二次出现的位置
		System.out.println(show+"第"+size+"次出现的位置是：" + i);
		return i;
	}
	

	private void addFileDropTarget(JTextField txt,boolean canDir) {
		new DropTarget(txt, DnDConstants.ACTION_COPY_OR_MOVE, new DropTargetAdapter() {
			@Override
			public void drop(DropTargetDropEvent dtde) {
				try {
					if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
					    // 接收拖拽目标数据
					    dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);

					    // 以文件集合的形式获取数据
					    List<File> files = (List<File>) dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
					    if (!canDir) {
					    	files=files.stream().filter(e->!e.isDirectory()).collect(Collectors.toList());
						}

					    // 把文件路径输出到文本区域
					    if (files != null && files.size() > 0) {
					        StringBuilder filePaths = new StringBuilder();
					        for (File file : files) {
					            filePaths.append(";" + file.getAbsolutePath());
					        }
					        filePaths.deleteCharAt(0);
					        txt.setText(filePaths.toString());
					        dtde.dropComplete(true);
					    }
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, true);
	}

	private void init() {
		MyAppender.list.add(new MyAppender.LogCallback() {
			@Override
			public void log(String s) {
				txt_msg.append(s);
				int length = txt_msg.getText().length();
				txt_msg.select(length, length);
			}
		});
	}
}
